<template>
  <div class="form-layout">
    <!--左侧导航-->
    <div class="nav-left">
      <customAnchor
        :itemList="[
          { name: 'box-base', title: '基本信息' },
          { name: 'box-dtl', title: '出库明细' },
        ]"
      />
    </div>

    <!--表单区域-->
    <div class="form-right" ref="formRight">
      <div id="box-base" class="box-title">基础信息</div>
      <customForm :data="form" :rules="propRules" ref="editForm" :disabled="propReadonly">
        <template #content>
          <customFormItem
            label="出库单号" name="busKey" :parent="_self" :form="form"
            disabled
            :config="{defaultValue: '系统自动生成'}"
          />

          <customFormItem
            label="出库日期" name="busDate" :parent="_self" :form="form"
            :type="constCommon.formItemType.datePicker.name" :disabled="cpHasDtl"
          />

          <customFormItem
            label="出库人" name="busUser" :parent="_self" :form="form" :disabled="cpHasDtl"
          />

          <customFormItem
            label="出库仓库" name="warehouseName" :parent="_self" :form="form"
            :readonly="true" :showSelectIcon="true"
            @focus="utilSelect.warehouse(warehouseChange)"
            :disabled="cpHasDtl"
            help="有明细后不可修改"
          />

          <customFormItem
            label="出库类型"
            name="busType"
            :parent="_self"
            :form="form"
            :type="constCommon.formItemType.selectStatic.name"
            :config="{ options: utils.getDictDataList(constCommon.dictType.outOrderType) }"
            disabled
          />

          <customFormItem label="出库总金额" name="amount" :parent="_self" :form="form"
           :type="constCommon.formItemType.inputNumber.name" disabled />

           <customFormItem
            label="供应商"
            name="supplierName"
            :parent="_self"
            :form="form"
            :readonly="true"
            :showSelectIcon="true"
            @focus="utilSelect.supplier(supplierChange)"
            :disabled="cpHasDtl"
            help="保存后不可修改"
          />

          <customFormItem label="寄售" name="flagConsignment" :parent="_self" :form="form"
                          :type="constCommon.formItemType.switch.name"
                          :config="{flagValueBoolean: true}" :disabled="cpHasDtl"
          />

          <customFormItem label="标签管理" name="flagOmoc" :parent="_self" :form="form"
                          :type="constCommon.formItemType.switch.name"
                          :config="{flagValueBoolean: true}" :disabled="cpHasDtl"
          />

          <customFormItem
            label="备注" name="remark" :parent="_self" :form="form"
          />
        </template>
      </customForm>

      <div id="box-dtl" class="box-title">出库明细</div>
      <customTooltip v-show="cpIsAddDtl">
        <template #title>
          选择库存
        </template>
        <template #content>
          <FortenScan
            ref="scanInputDtl"
            propPlaceholder="扫描唯一码进行添加或者取消"
            @after-scan="barCodeScan"
            propType="uniqueCode"
            style="width: 300px;margin-top: 10px;display: inline-block; margin-right: 5px"/>

            <customButton
            title="选择库存"
            theme="primary"
             @click="utilSelect.stockMore(selectChangeStock, form.warehouseId, form.flagOmoc, true, true, null, form.flagConsignment, form.supplierId,'', constCommon.dictType.wmInOrderTypeInNumber)"
              />
        </template>
      </customTooltip>
      <data-view
        propViewKey="wm_out_order_item"
        :propInitData="form"
        :propParentData="propParent.viewFormData"
        ref="childDataView"
        :propsDisableDbClick="true"
        :propParentPage="_self"
        :propAutoFetchData="false"
        @extra-button-click="extraButtonClick"
        :propHideFlowSelect="true"
        @afterTableDataChange="afterTableDataChange"
        :propFlowKey="propParent.propFlowKey"
        :propNoEditRow="true"
      />
    </div>

  </div>
</template>

<script>
import customAnchor from '@/components/custom/form/customAnchor.vue'

export default {
  data() {
    return {
      form: {},
      viewData: {},
      txtScan: '',
    }
  },
  computed: {
    // 是否有明细
    cpHasDtl() {
      return this.form.countDtl > 0
    },
    // 出库消耗
    cpQueries() {
      let wrapper = this.$newWrapper()
      wrapper.eq('warehouseId', this.form.fromWarehouseId)
        .eq('flagConsignment', this.form.flagConsignment)
        .eq('flagOmoc', this.form.flagOmoc)
        .gt('sku_qty', 0)
        .eq('lockQty', 0)

      if (this.strings.isNotBlank(this.form.supplierId)) {
        wrapper.eq('supplierId', this.form.supplierId)
      }
      return wrapper
    },
     // 是否可以添加明细
     cpIsAddDtl() {
      return this.form.flowStatus == 'start'
    },
  },
  methods: {
    loadDtl() {
      if (!this.$refs.childDataView) {
        return
      }
      let $newWrapper = this.$newWrapper()
      if (!this.propParent.cpFormNew) {
        $newWrapper.eq('workOrderId', this.form.id)
      } else {
        $newWrapper.ne(1, 1)
      }
      this.$refs.childDataView.setQueryWrapper($newWrapper)
    },
    //扫码SN或RFID
    barCodeScan(txtScan) {
      this.utilVue.loadShow(true)
      const params = {
        'workOrderId': this.form.id,
        'uniqueCode': txtScan,
        ...this.form,
      }
      this.$ajax.post('/wm/out_order_item/scan',params
      ).then(
        resp => {
          if (resp.code == 0) {
            this.utilMessage.success(resp.msg)
            this.loadDtl()
            this.afterTableDataChange()
            this.$set(this.$data, 'txtScan', null)
          }
          this.utilVue.loadHide()
        }
      )
    },

    // 明细 新增、删除、修改后调用
    afterTableDataChange() {
      this.utils.refreshRefs(this)
    },

    // 根据明细设置表单属性
    setFormByDtl(dtl) {
      this.$set(this.form, 'flagOmoc', dtl.flagOmoc)
      this.$set(this.form, 'flagConsignment', dtl.flagConsignment)
      this.$set(this.form, 'supplierId', dtl.supplierId)
      this.$set(this.form, 'supplierName', dtl.supplierName)
  },

    // 添加明细
    _saveBatchItem(matrList) {
      this.utilVue.loadShow(true)
      let listSn = new Array()
      matrList.forEach(item => {
       if (item.supplierId === this.form.supplierId
          && item.flagConsignment === this.form.flagConsignment
          && item.warehouseId === this.form.warehouseId
          && item.flagOmoc === this.form.flagOmoc) {
          listSn.push(item.sn)
        }
      })
      const params = {
        workOrderId: this.form.id,
        warehouseId: this.form.warehouseId,
        supplierId: this.form.supplierId,
        flagConsignment: this.form.flagConsignment,
        flagOmoc: this.form.flagOmoc,
        listSn
      }
      this.$ajax.post('/wm/out_order_item/addBySelect', params).then((resp) => {
        this.utilVue.loadHide()
        if (resp.code == 0) {
          this.utilMessage.success(resp.msg)
          this.loadDtl()
          this.afterTableDataChange()
        }
      })
    },

    // 库存选择后
    selectChangeStock(rows) {
      let rowFirst = rows[0]
      let matrAddList = rows.filter(
          item => item.id !== rowFirst.id
            && item.flagOmoc == rowFirst.flagOmoc
            && item.flagConsignment == rowFirst.flagConsignment
            && item.supplierId == rowFirst.supplierId
      )

      matrAddList.push(rowFirst)
      if (rows.length != matrAddList.length) {
          this.utilMessage.confirm(`所选择的数据中，有${rows.length - matrAddList.length}条属性不一致，已忽略。是否提交?`, () => {
            //主单据未保存
            if(this.propParent.cpFormNew) {
              this.setFormByDtl(rowFirst)
              this.propParent.ocAsynSaveViewForm(() => {
                this._saveBatchItem(matrAddList)
              })
            }
          })
          return
      }

      //主单据未保存
      if (this.propParent.cpFormNew) {
        this.setFormByDtl(rowFirst)
        this.propParent.ocAsynSaveViewForm(() => {
          this._saveBatchItem(matrAddList)
        })
        return
      }
      this._saveBatchItem(matrAddList)
    },

    // 扩展按钮事件
    extraButtonClick() {
      // let buttonKey = button.key
      // if (buttonKey === 'chooseStock') { // 选择商品
      //   this.$refs.tableDrawerDtl.show(this.saveBatchItem, true)
      // }
    },

    addNewInit() {
      if (this.strings.isNotBlank(this.utils.getCurrentWarehouse().warehouseId)) {
        this.$set(this.form, 'warehouseId', this.utils.getCurrentWarehouse().warehouseId)
        this.$set(this.form, 'warehouseName', this.utils.getCurrentWarehouse().warehouseName)
      }
      this.$set(this.form, 'busUser', this.utils.getCurrentUser().name)
      this.$set(this.form, 'busDate', new Date().format(this.dates.defaultDateTimePattern))
      this.$set(this.form, 'busType', this.constCommon.dictType.wmOutOrderTypeOutNumber)
      this.$set(this.form, 'flagConsignment', true)
      this.$set(this.form, 'flagOmoc', false)
    },

     // 选择结算类型
    settlementTypeChange(value) {
      this.$set(this.form, 'settlementType', value)
    },

    // 仓库 选择
    warehouseChange(row) {
      this.$set(this.form, 'warehouseName', row.name)
      this.$set(this.form, 'warehouseId', row.id)
    },
    // 供应商选择
    supplierChange(row) {
      this.$set(this.form, 'supplierId', row.id)
      this.$set(this.form, 'supplierName', row.name)
    },
  },
  created() {
    let that = this
    this.$emit('event-register', {
      validate: (callback) => {
        return this.$refs.editForm.validate(callback)
      },
      beforeSave: () => {
        this.$emit('data-callback', this.form)
        return true
      },
      afterMove: (formData, initData) => {
        this.form = global.utils.jsonClone(formData)
        // 设置元素默认值
        if (!this.form.id) {
          this.addNewInit()
        }
        this.loadDtl()
      },
      afterSave: () => {  },
      beforeDelete: () => {
        return true
      },
      afterDelete: () => {
      },
      beforeFlow: (flowButtonKey) => {
        if (flowButtonKey == 'submit') {
          if (this.form.countDtl == 0) {
            this.utilMessage.error('退货明细为空，不能提交')
            return false
          }
        }

        return true
      },
      afterFlow: (flowButtonKey) => {
      },
      beforeClose: () => {
        return true
      },
      async afterClick(button, data, viewForm) {
        let {key: buttonKey} = button
        if (buttonKey == 'preview') { //打印明细
          let param = {
            'that': that, //当前调用对象
            configList: [ //打印配置，可以多个
              {
                //打印配置
                printBusType: 'deptReturn', //打印业务类型，来源print_template.bus_type，同constPrint.busKey
                //主单据数据或者数据查询配置
                formData: that.form, //数据对象
                formDataId: that.form.id,
              }
            ]
          }
          global.utilPrint.openFormPrint(param)
        } else if (buttonKey == 'printSum') { //打印汇总
          let param = {
            'that': that, //当前调用对象
            configList: [ //打印配置，可以多个
              {
                //打印配置
                printBusType: 'deptReturnSum', //打印业务类型，来源print_template.bus_type，同constPrint.busKey
                //主单据数据或者数据查询配置
                formData: that.form, //数据对象
                formDataId: that.form.id,
              }
            ]
          }
          global.utilPrint.openFormPrint(param)
        }
      },
    })
  },
  props: {
    propParent: Object,
    propInitData: Object,
    propPrimaryKey: String,
    propDictionaries: Object,
    propCurrentRow: Object,
    propViewFormData: Object,
    propReadonly: Boolean,
    propStatus: String,
    propRules: Object,
    propFlowKey: String,
    propParam: Object
  },
  components: {
    customAnchor
  },
}
</script>
